#!/usr/bin/env python3
# Copyright (c) 2019-2020 Windy Albert


import hashlib
import binascii
import hmac
import ecdsa
import os
import base58check

from keyTree import *



class addrDOGE(object):
    def __init__(self, obj):
        self.obj = obj
    
    def getWallet(self,pa):
        xprv = keyTree().getChildpriKey(self.obj,pa)
        xprv_hex = base58check.b58decode(xprv["xprv"])
        prikey_hex = xprv_hex[46:78].hex()
        data = "9e"+prikey_hex + "01" #compressed
        sha256_1 = hashlib.new('sha256',bytes.fromhex(data))
        sha256_2 = hashlib.new('sha256',bytes.fromhex(sha256_1.hexdigest()))
        wif_b58 = base58check.b58encode(bytes.fromhex(data+(sha256_2.hexdigest())[0:8]))

        path = self.obj["path"] + "/" + pa
        wif = str(wif_b58,'utf-8')
        pubkey = self.getPubkey(wif)
        addr = self.getAddr( pubkey )
        return {"path":path,"wif":wif,"addr":addr}

    def __getPubkeyID(self,pubkey):
        # wif_hex = base58check.b58decode(wif)
        # prikey = wif_hex[1:33]
        # sk = ecdsa.SigningKey.from_string( bytes.fromhex(prikey.hex()), curve=ecdsa.SECP256k1)    
        # vk = sk.get_verifying_key() #this is your verification key (public key)
        # public_key = vk.to_string("compressed").hex()
        sha256  = hashlib.new('sha256',bytes.fromhex(pubkey))
        hash160 = hashlib.new('ripemd160',bytes.fromhex(sha256.hexdigest()))
        return (hash160.hexdigest())

    def getAddr(self,pubkey):
        pubkeyID = self.__getPubkeyID(pubkey)
        data = "1e" + pubkeyID
        sha256_1 = hashlib.new('sha256',bytes.fromhex(data))
        sha256_2 = hashlib.new('sha256',bytes.fromhex(sha256_1.hexdigest()))
        addr = base58check.b58encode(bytes.fromhex(data+(sha256_2.hexdigest())[0:8]))
        return addr.decode('utf-8')

    def getPubkey(self,wif):
        wif_hex = base58check.b58decode(wif)
        prikey = wif_hex[1:33]
        sk = ecdsa.SigningKey.from_string( bytes.fromhex(prikey.hex()), curve=ecdsa.SECP256k1)    
        vk = sk.get_verifying_key() #this is your verification key (public key)
        public_key = vk.to_string("compressed").hex()
        return public_key


def main():
    print("This is demo ...")

    # xprv = "xprvA1guPivSuKxFx9TqVkYCNDfkrBgkvTntA3hgKr8SERDkcNtJgFRe9MxXxCD75aQQWm1EEPxfJE3nmeVE39sXg2SZQN4w8dgYrJnVJBMrPfM"
    # addrOBJ = addrDOGE(xprv)


if __name__ == '__main__':
    main()